package com.haust.community.interceptor;

import com.haust.community.pojo.User;
import com.haust.community.service.DataService;
import com.haust.community.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: csp1999
 * @Date: 2020/12/03/18:34
 * @Description: 访问统计UV(独立访客)/DAI(日活跃用户)的拦截器
 */
@Component
public class DataInterceptor implements HandlerInterceptor {

    @Autowired
    private DataService dataService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 统计UV(独立访客)
        // 获得访客的IP
        String ip = request.getRemoteHost();
        // 将指定的IP计入UV
        dataService.recordUV(ip);

        // 统计DAU(日活跃用户)
        // 获取登录用户对象
        User user = hostHolder.getUser();
        if (user != null) {
            // 将指定用户计入DAU
            dataService.recordDAU(user.getId());
        }
        return true;
    }
}
